//table api
const Service = require('egg').Service;
const tables = require("../public/tables.js")

class TableService extends Service {
    //生成表(初始化表数据内容)
    async create(tabName, total) {
        let { service, app } = this;
        let currTabInfo = tables.filter((table, ind) => table.name == tabName)[0];
        let currTabMeth = service.get.fileds[tabName];
        let result = await service.get.table.initData(currTabInfo, currTabMeth, total);
        let init = async (result, endArr = []) => {
            if (result.tabName) {
                let { tabName, fieldsStr, valuesStr, foreigns } = result;
                tabName = this.service.utility.toWriteMode(tabName, "mode_type");
                let truEnd = await this.truncate(tabName);
                if (truEnd.warningCount == 0) {
                    let sql = `insert into ${tabName} (${fieldsStr}) values ${valuesStr}`;
                    let end = await this.app.mysql.query(sql);
                    end.tabName=tabName;
                    if (end.affectedRows > 0) {
                        endArr.push(end);
                        for (let i = 0; i < foreigns.length; i++) {
                            end = await init(foreigns[i], endArr);
                        }
                    }
                } else {
                    return truEnd;
                }
            }
            return endArr;
        }
        return init(result);
    }
    //清空表
    async truncate(tabName) {
        let { service, app } = this;
        tabName = service.utility.toWriteMode(tabName, "mode_type");
        let end = await app.mysql.query(`truncate ${tabName}`);
        return end;
    }
}
module.exports = TableService;